﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.CompilerServices;
using TuyennvLibrary.SqlClient;
namespace TuyennvLibrary.ServerApi.Models
{
    public class ErrorLog
    {
        public long id { get; set; }
        public int type_error { get; set; }
        public string content { get; set; }
        public DateTime createddate { get; set; }


        public static string COLUMN_ID = "id";
        public static string COLUMN_TYPE_ERROR = "type_error";
        public static string COLUMN_CONTENT = "content";
        public static string COLUMN_CREATEDDATE = "createddate";


        public static string TableName = "ErrorLog";

        public ErrorLog()
        {
            this.id = 0;
            this.type_error = 0;
            this.content = string.Empty;
            this.createddate = DateTime.Now;

        }
    }
    public class ErrorLogModel : BaseModel<ErrorLog>
    {
        public ErrorLogModel()
        {
            table = ErrorLog.TableName;
        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        public bool Insert(ErrorLog obj)
        {
            try
            {
                DB.Insert(table, new SqlParameter[] {
					new SqlParameter("type_error",obj.type_error),
					new SqlParameter("content",obj.content),
					new SqlParameter("createddate",obj.createddate),
                    
                });
                return true;


            }
            catch (Exception)
            {

                throw;
            }
        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        public bool Update(ErrorLog obj)
        {
            try
            {
                DB.Update(table, new SqlParameter[] {
					new SqlParameter("type_error",obj.type_error),
					new SqlParameter("content",obj.content),
					new SqlParameter("createddate",obj.createddate),

                }, new SqlParameter[]{
					new SqlParameter("id",obj.id),
															 
                });
                return true;


            }
            catch (Exception)
            {

                throw;
            }
        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        public bool Delete(long id)
        {
            try
            {
                DB.Delete(table, new SqlParameter[] { 
					new SqlParameter("id",id),
															 
                });
                return true;
            }
            catch (Exception)
            {

                throw;
            }
        }
        public bool DeleteMulti(string[] ListID)
        {
            try
            {
                if (ListID !=null&&ListID.Length>0)
                {
                    foreach (string ID in ListID)
                    {
                        Delete(int.Parse(ID));
                    }
                }
                return true;
            }
            catch (Exception)
            {

                throw;
            }
        }
        public bool DeleteMulti(string ListID)
        {
            try
            {
                if (ListID != string.Empty)
                {
                    foreach (string ID in ListID.Split(','))
                    {
                        Delete(int.Parse(ID));
                    }
                }
                return true;
            }
            catch (Exception)
            {

                throw;
            }
        }
        public List<ErrorLog> GetByPage(int page, int pagesize, List<ErrorLog> source)
        {
            List<ErrorLog> list = new List<ErrorLog>();
            int index = (page - 1) * pagesize;
            int count = source.Count;
            if (pagesize > count)
                list = source;
            else if (pagesize > count - index)
                list = source.GetRange(index, count - index);
            else
                list = source.GetRange(index, pagesize);
            return list;
        }
        public List<ErrorLog> GetListBy(DataTable dt)
        {
            List<ErrorLog> list = new List<ErrorLog>();
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    ErrorLog obj = GetBy(dr);
                }
            }
            return list;
        }
        public DataTable GetListAll()
        {
            try
            {
                DataTable dt = DB.SelectDataTable(table);
                return dt;
            }
            catch (Exception)
            {

                throw;
            }
        }
        public DataTable GetListBy(string content,int type_error,string fromday, string targetDay)
        {
            try
            {
                string query = string.Format("select * from ErrorLog where createddate>=CONVERT(datetime,'{0}',103) and createddate<=CONVERT(datetime,'{1}',103)", fromday + " 00:00:00", targetDay + " 23:59:59");
                if (!string.IsNullOrEmpty(content))
                {
                    query += string.Format(" and content like '%{0}%'",content);
                }
                if (type_error != 0)
                {
                    query += string.Format(" and type_error={0}", type_error);
                }
                if (this.page > 0)
                {
                    this.Count = GetCountBy(query);
                    query = GetQueryPagging(query, "createddate desc", page, pagesize);
                }
                DataTable dt = DB.ExecuteDataTable(query, null);
                return dt;
            }
            catch (Exception)
            {

                throw;
            }
        }
        public ErrorLog GetBy(DataRow dr)
        {
            try
            {
                ErrorLog obj = new ErrorLog();
                obj.id = (dr["id"] is DBNull) ? 0 : long.Parse(dr["id"].ToString());
                obj.type_error = (dr["type_error"] is DBNull) ? 0 : int.Parse(dr["type_error"].ToString());
                obj.content = (dr["content"] is DBNull) ? string.Empty : dr["content"].ToString();
                obj.createddate = (dr["createddate"] is DBNull) ? DateTime.Now : DateTime.Parse(dr["createddate"].ToString());

                return obj;
            }
            catch (Exception)
            {
            }

            return new ErrorLog();
        }
        public ErrorLog GetBy(DataTable dt)
        {
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    return GetBy(dr);
                }
            }
            return new ErrorLog();
        }
        public ErrorLog GetByID(long id)
        {
            try
            {
                DataTable dt = DB.SelectDataTable(null, table, new SqlParameter[] { 
					new SqlParameter("id",id),
															
                }, null);
                return GetBy(dt);
            }
            catch (Exception)
            {

                throw;
            }
        }
        public static bool logError(TypeError type_error, string content)
        {
            ErrorLogModel errorlogModel = new ErrorLogModel();
            ErrorLog error = new ErrorLog();
            error.type_error = (int)type_error;
            error.content = content;
            return errorlogModel.Insert(error);
        }
        /// <summary>
        /// Ghi lỗi cho các kịch bản SMS
        /// </summary>
        /// <param name="command">Mã SMS nhận được</param>
        /// <param name="people">Tên đầy đủ người ghi log lỗi</param>
        /// <param name="content">Nội dung lỗi</param>
        /// <returns></returns>
        public static bool logErrorSMS(string command, string people, string content)
        {
            content = string.Format("command: {0} - people: {1} - info: {2}", command, people, content);
            return logError(TypeError.Sms, content);
        }
        /// <summary>
        /// Ghi lỗi cho các kịch bản API
        /// </summary>
        /// <param name="classapi">Tên class API đang sử dụng</param>
        /// <param name="people">Tên đầy đủ người ghi log lỗi</param>
        /// <param name="content">Nội dung lỗi</param>
        /// <returns></returns>
        public static bool logErrorAPI(string classapi, string people, string content)
        {
            content = string.Format("class: {0} - people: {1} - info: {2}", classapi, people, content);
            return logError(TypeError.Api, content);
        }
    }
}
